"""
Created on 2022-05-26
@author:刘飞
@description:用户模块依赖注入
"""
from fastapi import Request
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from sqlalchemy.orm import Session
from apps.user import schemas
from apps.user import models
from databases import SessionLocal
from utils.custom_config import SECRET_KEY, ALGORITHM


# 数据库依赖【需要数据库操作的路由用这个】
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/user/login")


# 返回当前用户依赖
async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    """用户验证依赖"""
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无法验证凭据",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    user = db.query(models.User).filter(models.User.username == username).first()
    if user is None:
        raise credentials_exception
    return user


# 确认用户已激活依赖
async def get_current_active_user(current_user: schemas.BaseUser = Depends(get_current_user)):
    if not current_user.is_active:
        raise HTTPException(status_code=400, detail="用户未激活")
    return current_user
